<?php


namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Exception;

class Test extends Controller
{
    /**
     * 注册会员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function cardAdd($personsCreate,$cardNos){

        //获取token
        $token = $this->token();
        $black = $this->personsCreate($personsCreate,$token);
        Db::name("tickets_list")->where(['signcode'=>$personsCreate['employeeNo']])->update(['status'=>1]);
        if($black['code']!=200){
            return $black;
        }

        //绑定卡号
        foreach ($cardNos as $k=>$item){
            $this->batchCreate($item,$personsCreate['employeeNo'],$token);
        }
        //绑定权限组
        $this->addPersons([$personsCreate['employeeNo']],$token);
        return true;
    }


    /**
     * 批量删除过期人员
     * @author zhixuedong
     * @date 2021/2/19/019
     */
    public function batchDel(){
        //获取token
        $token = $this->token();
        $list = $this->getEmployeeNos();
        $list = $list['data']['rows'];
        $nowtime = time();
        foreach ($list as $item){
            $employeeNo = $item['employeeNo'];
            $black = $this->personFace($employeeNo,$token);
            if($black['code']==200){
                $detail = $black['data'];
                $validEndTime = strtotime($detail['validEndTime']);
                if($nowtime>$validEndTime){
                    Db::name("tickets_list")->where(['signcode'=>$employeeNo])->update(['status'=>2]);
                    //删除人员
                    $this->personsDelete($employeeNo,$token);
                    //删除卡号
                    $this->deletePersonCards([$employeeNo],$employeeNo,$token);
                    //权限组人员解绑
                    $this->removePersons([$employeeNo],$token);
                }
            }
        }
        echo "操作成功";
    }


    /**
     * 更新人员信息
     * @author zhixuedong
     * @date 2021/2/19/019
     */
    public function personsUpdate($post_data,$type=0){
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/persons/update";
//        $post_data['personName'] = "F22741861";
//        $post_data['employeeNo'] = "YQ0001202101311199504231a3";
////        $post_data['faceImageBase64'] = "https://tickets-1253901423.cos.ap-nanjing.myqcloud.com/platform1/2021-02-03/79882db2dc322e5184f162885f04c5e8.jpg";

//        $startTime = date("Y-m-d\T00:00:01P",time());
//        $endtTime = date("Y-m-d\T23:59:59P",time());
//        $post_data['validBeginTime'] = $startTime;
//        $post_data['validEndTime'] = $endtTime;
        if(!empty($post_data['faceImageBase64'])){
            $base64 = $this->imgToBaes64($post_data['faceImageBase64']);
            $post_data['faceImageBase64'] = $base64;
        }
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);

        if($type==1){
            $black = json_decode($black,true);
            if($black['code']!=200){
                throw new Exception($black['message']);
            }
        }else{
            return json_decode($black,true);
        }
    }

    /**
     * 获取人员详情
     * @return mixed
     * @author zhixuedong
     * @date 2021/2/19/019
     */
    public function personFace($employeeNo,$token){
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/persons/get?employeeNo=".$employeeNo;
        $black = $this->curl_file_get_contents($url,$token['access_token']);
//        $black = json_decode($black,true);
        return json_decode($black,true);
    }


    function imgToBaes64($url)
    {
        $imgInfo = getimagesize($url);
        return base64_encode(file_get_contents($url));
        //return 'data:'.$imgInfo['mime'].';base64,'.base64_encode(file_get_contents($url));
    }

    /**
     * 获取token值
     * @return mixed
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function token(){
        $url = "https://api2.hik-cloud.com/oauth/token";
        $post_data['client_id'] = "fcde8b7ff3234f85a480a646ad017cde";
        $post_data['client_secret'] = "f04450ad71644bb6a3ba6426cb10f665";
        $post_data['grant_type'] = "client_credentials";
        $black = $this->send_post($url,$post_data);
        $black = json_decode($black,true);
        return $black;
    }




    /**
     * 注册会员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function cardAdd2(){
        $personsCreate['employeeNo'] = "YQ000120210131119951";
        $cardNos = ['YQ000120210131119951','421127198910040813'];
        $personsCreate['personName'] = "测试人员";
        $cardType = ['normalCard','superCard','patrolCard'];

        //$post_data['faceImageBase64'] = "https://tickets-1253901423.cos.ap-nanjing.myqcloud.com/platform1/2021-02-03/79882db2dc322e5184f162885f04c5e8.jpg";
        if(!empty($post_data['faceImageBase64'])){
            $base64 = $this->imgToBaes64($post_data['faceImageBase64']);
            $post_data['faceImageBase64'] = $base64;
        }
        $startTime = date("Y-m-d\T00:00:01P",time());
        $endtTime = date("Y-m-d\T23:59:59P",time());
        $personsCreate['validBeginTime'] = $startTime;
        $personsCreate['validEndTime'] = $endtTime;

//        $personsCreate['employeeNo'] = "AI0001040003708eba6f";
//        $cardNos = ['AI0001040003708eba6f','42058219921108359X'];
//        $personsCreate['personName'] = "支雪冬1";
        //获取token
        $token = $this->token();
        $black = $this->personsCreate($personsCreate,$token);
        if($black['code']!=200){
            throw new Exception($black['message']);
        }
        //绑定卡号
        foreach ($cardNos as $k=>$item){
            $black1 = $this->batchCreate($item,$personsCreate['employeeNo'],$token);
        }
        //绑定权限组
        $this->addPersons([$personsCreate['employeeNo']],$token);
        echo "绑定成功";
    }


    public function cardAdd1(){
        $personsCreate['employeeNo'] = "YQ000120210131119950";
        $cardNos = ['YQ000120210131119950','421127198910040812'];
//        $cardType = ['normalCard','superCard','patrolCard'];
        $token = $this->token();

        //绑定卡号
        foreach ($cardNos as $k=>$item){
            dump($item);
            $black = $this->batchCreate($item,$personsCreate['employeeNo'],$token);
            dump($black);
        }
        die;
    }



    /**
     * 删除会员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function cartDel($employeeNo){
        //获取token
        $token = $this->token();
        //删除人员
        $black = $this->personsDelete($employeeNo,$token);
        //删除卡号
        $this->deletePersonCards([$employeeNo],$employeeNo,$token);
        //权限组人员解绑
        $this->removePersons([$employeeNo],$token);
        return true;
    }

    /**
     * 清空人员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function clean(){
        //获取token
        $token = $this->token();
        $list = $this->getEmployeeNos();

        $list = $list['data']['rows'];


        if(!empty($list)){
            foreach ($list as $item){
                $employeeNo = $item['employeeNo'];
                Db::name("tickets_list")->where(['signcode' => $employeeNo])->update(['status' => 2]);
                //删除人员
                $this->personsDelete($employeeNo,$token);
                //删除卡号
                $this->deletePersonCards([$employeeNo],$employeeNo,$token);
                //权限组人员解绑
                $this->removePersons([$employeeNo],$token);
            }
        }


       return true;
    }


    /**
     * 新增卡片
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function batchCreate($cardNo,$employeeNo,$token){
        //获取token
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/cards/batchCreate";
        $cards['cardNo'] = $cardNo;
//        $cards['cardType'] = $normalCard;
        $cards['employeeNo'] = $employeeNo;
        $post_data['cards'][] = $cards;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 删除卡片
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function batchDelete(){
        //获取token
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/cards/batchDelete";
        $cards = ['F22741861'];
        $post_data['cardNos'] = $cards;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 根据人员编号删除卡片
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function deletePersonCards($cards,$employeeNo,$token){
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/cards/deletePersonCards";
        $post_data['cardNos'] = $cards;
        $post_data['employeeNo'] = $employeeNo;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 创建人员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function personsCreate($post_data,$token,$type=0){
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/persons/create";
//        $post_data['personName'] = "F22741861";
//        $post_data['employeeNo'] = "F22741861";
        if(!empty($post_data['faceImageBase64'])){
            $base64 = $this->imgToBaes64($post_data['faceImageBase64']);
            $post_data['faceImageBase64'] = $base64;
        }
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);

        if($type==1){
            $black = json_decode($black,true);
            if($black['code']!=200){
                throw new Exception($black['message']);
            }
        }else{
            return json_decode($black,true);
        }
    }

    /**
     * 删除人员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function personsDelete($employeeNo,$token){
//        $employeeNo = "F22741861";
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/persons/delete?employeeNo=".$employeeNo;
        $post_data = [];
        $black = $this->curl_file_post_contents($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }


    /**
     * 权限组新增
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function permissionGroupsCreate(){
        //获取token  9a7644e41a964465939bc117506d1790
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/create";
        $post_data['groupName'] = "本地测试组";
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 权限组删除
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function permissionGroupsDelete(){
        //获取token
        $token = $this->token();
        $groupId = "9a7644e41a964465939bc117506d1790";
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/delete?groupId=".$groupId;
        $post_data = [];
        $black = $this->curl_file_post_contents($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 权限组列表
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function permissionGroupsList(){
        //获取token
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/page";
        $post_data['pageNo'] = 1;
        $post_data['pageSize'] = 10;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        $black = json_decode($black,true);
        return json_decode($black,true);
    }

    /**
     * 权限组绑定人员
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function addPersons($employeeNos,$token){
        //获取token
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/addPersons";
        $post_data['groupId'] = 'f3eb24693d124ddd9a2cf86af674d840';
        $post_data['employeeNos'] = $employeeNos;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        return json_decode($black,true);
    }

    /**
     * 权限组获取人员编号列表
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function getEmployeeNos(){
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/getEmployeeNos";
        $post_data['groupId'] = 'f3eb24693d124ddd9a2cf86af674d840';
        $post_data['pageNo'] = 1;
        $post_data['pageSize'] = 1000;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
//        $black = json_decode($black,true);
        return json_decode($black,true);
    }


    /**
     * 9a7644e41a964465939bc117506d1790 本地测试组
     * f3eb24693d124ddd9a2cf86af674d840  游客权限组
     * @return mixed
     * @author zhixuedong
     * @date 2021/2/24/024
     */
    public function getEmployeeNos1(){
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/getEmployeeNos";
        $post_data['groupId'] = 'f3eb24693d124ddd9a2cf86af674d840';
        $post_data['pageNo'] = 1;
        $post_data['pageSize'] = 1000;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
        $black = json_decode($black,true);
        dump($black['data']['rows']);die;
        return json_decode($black,true);
    }

    /**
     * 权限组人员解绑
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function removePersons($employeeNos,$token){
        //获取token
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/permissionGroups/actions/removePersons";
        $post_data['groupId'] = 'f3eb24693d124ddd9a2cf86af674d840';
        $post_data['employeeNos'] = $employeeNos;
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);
//        $black = json_decode($black,true);
        //dump($black['data']['rows']);
        return json_decode($black,true);
    }


    /**
     * 远程开门
     * @return bool|mixed
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function deviceOpen(){
        //获取token
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/remoteControl/actions/open";
        $post_data['deviceSerial'] = empty($_GET['deviceSerial'])?"F22741861":$_GET['deviceSerial'];
        $post_data = json_encode($post_data);
        $black = $this->http_post_json($url,$post_data,$token['access_token']);

        dump($black);die;
        return json_decode($black,true);
    }


    //获取设备列表
    public function devicesList(){
        $token = $this->token();
        $url = "https://api2.hik-cloud.com/api/v1/open/basic/devices/list?groupNo=0&pageNo=1&pageSize=50";
        $black = $this->curl_file_get_contents($url,$token['access_token']);

//        $black = json_decode($black,true);
//        dump($black);die;
        return json_decode($black,true);
    }

    /**
     * 设备本地事件查询
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function deviceList(){
        $token = $this->token();
        $startTime = date("Y-m-d\TH:i:sP",time());
        $endtTime = date("Y-m-d\TH:i:sP",strtotime('-1minute',time()));
        $startTime = urlencode($startTime);
        $endtTime = urlencode($endtTime);
//        $major = [1,6,7,8,9,21,22,75,76,1024];
        $major = [1,75];
        $devicesList = $this->devicesList();

        $majordesc = ['1'=>'刷卡开锁','75'=>'人脸开锁'];
        foreach ($devicesList['data']['rows'] as $key=>$val){
            foreach ($major as $k=>$v){
                $url = "https://api2.hik-cloud.com/api/v1/open/accessControl/accessEvents/actions/list?pageNo=1&pageSize=100&deviceSerial=".$val['deviceSerial']."&major=5&minor=".$v."&startTime=".$startTime."&endTime=".$endtTime;
                $html = $this->curl_file_get_contents($url,$token['access_token']);
                $html = json_decode($html,true);

                foreach ($html['data']['rows'] as $k1=>$v1){
                    $log['date_time'] = $v1['time'];
                    $log['employee_no'] = $v1['employeeNo'];
                    $log['card_no'] = $v1['cardNo'];
                    $log['device_serial'] = $val['deviceSerial'];
                    $log['device_name'] = $val['deviceSerial'];
                    $log['type'] = $v;
                    $log['description'] = $majordesc[$v];
                    $log['code'] = $v1['serialNo'];
                    Db::name("tickets_device_log")->insert($log);

                    //检票次数减一
                    $tickets['signcode'] = $v1['employeeNo'];
                    $degree = Db::name("tickets_list")->where($tickets)->value("degree");
                    $update = [];
                    $update['degree'] = $degree-1;
                    $update['check_time'] = time();
                    Db::name("tickets_list")->where($tickets)->update($update);
                    if($degree==0){
                        $this->cartDel($v1['employeeNo']);
                    }
                }

            }
        }
    }

    /**
     * post请求
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    public function curl_file_post_contents($durl, $post_data,$token){
        // header传送格式
        $headers = array(
            'Authorization: Bearer '.$token,
        );
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $durl);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, false);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, true);
        // 设置post请求参数
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        // 添加头信息
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        // CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // 不验证SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //执行命令
        $data = curl_exec($curl);
        // 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }


    /*
     *  php访问url路径，get请求
     */
    function curl_file_get_contents($durl,$token){
        // header传送格式
        $headers = array(
            'Authorization: Bearer '.$token,
        );
        // 初始化
        $curl = curl_init();
        // 设置url路径
        curl_setopt($curl, CURLOPT_URL, $durl);
        // 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
        // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
        // 添加头信息
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        // CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // 不验证SSL
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 执行
        $data = curl_exec($curl);
        // 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
        // 关闭连接
        curl_close($curl);

        // 返回数据
        return $data;
    }

    /**
     * post json 请求
     * @param $url
     * @param $jsonStr
     * @param $token
     * @return array
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    function http_post_json($url, $jsonStr,$token)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr),
                'Authorization: Bearer '.$token
                )
        );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        //echo $return_content."<br>";
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return  $return_content;
        return array($return_code, $return_content);
    }


    /**
     * post请求
     * @param $url
     * @param $post_data
     * @return false|string
     * @author zhixuedong
     * @date 2021/2/18/018
     */
    function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
                    'http' => array(
                    'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $postdata,
        'timeout' => 15 * 60 // 超时时间（单位:s）
        )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

}